import { PrismaClient } from '@prisma/client'
import { workflowLogger } from './logger'
import { executeComfyWorkflow } from './comfy'
import { EventEmitter } from 'events'

const prisma = new PrismaClient()
const executionEmitter = new EventEmitter()

// 工作流执行状态
interface ExecutionStatus {
    id: string
    workflowId: string
    userId: string
    status: 'pending' | 'running' | 'completed' | 'failed'
    progress: number
    result?: any
    error?: string
    startTime: Date
    endTime?: Date
}

// 执行状态管理
class ExecutionManager {
    private executions = new Map<string, ExecutionStatus>()

    // 开始执行
    async startExecution(workflowId: string, userId: string, params: any): Promise<string> {
        const executionId = `exec_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`

        const status: ExecutionStatus = {
            id: executionId,
            workflowId,
            userId,
            status: 'pending',
            progress: 0,
            startTime: new Date()
        }

        this.executions.set(executionId, status)
        workflowLogger.start(workflowId, userId, params)

        // 异步执行工作流
        this.executeWorkflow(executionId, workflowId, userId, params)
            .catch(error => {
                workflowLogger.error(workflowId, userId, error)
            })

        return executionId
    }

    // 获取执行状态
    getStatus(executionId: string): ExecutionStatus | undefined {
        return this.executions.get(executionId)
    }

    // 更新进度
    private updateProgress(executionId: string, progress: number, status: string) {
        const execution = this.executions.get(executionId)
        if (execution) {
            execution.progress = progress
            workflowLogger.progress(execution.workflowId, execution.userId, progress, status)
            executionEmitter.emit('progress', { executionId, progress, status })
        }
    }

    // 执行工作流
    private async executeWorkflow(executionId: string, workflowId: string, userId: string, params: any) {
        const execution = this.executions.get(executionId)
        if (!execution) return

        try {
            execution.status = 'running'
            this.updateProgress(executionId, 0, 'Started')

            // 获取工作流配置
            const workflow = await prisma.workflow.findUnique({
                where: { id: workflowId }
            })

            if (!workflow) {
                throw new Error('Workflow not found')
            }

            // 执行工作流
            const workflowConfig = JSON.parse(workflow.workflow)
            const result = await executeComfyWorkflow(workflowConfig, params)

            // 更新执行状态
            execution.status = 'completed'
            execution.result = result
            execution.endTime = new Date()
            this.updateProgress(executionId, 100, 'Completed')

            workflowLogger.complete(workflowId, userId, result)
            executionEmitter.emit('completed', { executionId, result })

        } catch (error: any) {
            execution.status = 'failed'
            execution.error = error.message
            execution.endTime = new Date()

            workflowLogger.error(workflowId, userId, error)
            executionEmitter.emit('failed', { executionId, error })
        }
    }

    // 清理过期执行记录
    cleanup(maxAge: number = 24 * 60 * 60 * 1000) { // 默认保留24小时
        const now = Date.now()
        for (const [id, execution] of this.executions.entries()) {
            if (execution.endTime && (now - execution.endTime.getTime() > maxAge)) {
                this.executions.delete(id)
            }
        }
    }
}

export const executionManager = new ExecutionManager()
export { executionEmitter }